#include "NetworkSyncableInt.h"

namespace mp_net
{
	
	NetworkSyncableInt::NetworkSyncableInt(
		const NetworkSyncDirection syncDirection)
		: NetworkSyncable(syncDirection)
	{
		m_val = 0;
	}

	NetworkSyncableInt::NetworkSyncableInt(const int val, 
		const NetworkSyncDirection syncDirection)
		: NetworkSyncable(syncDirection)
	{
		m_val = val;
	}

	void  NetworkSyncableInt::GetCharArray(char* data, int& arraySize)
	{
		//Set data to null for if grabbing data as a char array is not
		//  allowed.
		data = NULL;
		
		//Check if grabbing the char array is allowed
		if ( m_syncDirection == NetworkSyncDirection::OUT ||
			 m_syncDirection == NetworkSyncDirection::IN_OUT )
		{
			//Lock this object to generate the char array
			if (!TryLock()){;;}

			char size = sizeof(int) / sizeof(char);
			data = new char[size];
			for(char i = 0; i < size; i++)
			{
				data[i] = (char)((m_val >> (8*i)) & 0xFF);
			}

			m_syncStatus = NetworkSyncStatus::SYNCED;
			Unlock();

			arraySize = size;
		}
	}
		
	void  NetworkSyncableInt::SyncWithCharArray(const char* data, const int arraySize)
	{
		if ( m_syncDirection == NetworkSyncDirection::IN ||
			 m_syncDirection == NetworkSyncDirection::IN_OUT )
		{
			if (!TryLock()){;;}

			if ( arraySize != sizeof(int) / sizeof(char) )
				throw "Invalid char array to sync with";
			
			m_val = 0;
			for(int i = 0; i < arraySize; i++)
			{
				//m_val += (int)4;
				m_val += ( (int)(data[i] & 0xFF) << (8*i) );
			}

			m_syncStatus = NetworkSyncStatus::SYNCED;
			Unlock();
		}
	}

}